import {ADD_NEWS,
    DELETE_NEWS,
    QUERY_ALL_NEWS,
    QUERY_ALL_TOPNEWS,
    QUERY_ALL_NEWS_BYTYPE,
    QUERY_NEWS_DETAILS,
    QUERY_ALL_INFO_BYFLOOR
    } from './action-types'
//构造actioncreator
export const addNews=(news)=>{
    return {
        type:ADD_NEWS,
        payload:news
    }
}

export const deleteNews=(nid)=>{
    return {
        type:DELETE_NEWS,
        payload:nid
    }
}
export const queryAllNews=(newsList)=>{
    return {
        type:QUERY_ALL_NEWS,
        payload:newsList
    }
}
export const queryAllInfoByFloor=(watchList)=>{
    return {
        type:QUERY_ALL_INFO_BYFLOOR,
        payload:{watchList}
    }
}
//异步的actioncreator
export const queryAllInfoByFloorAsync=(fid)=>{
    return (dispatch)=>{
        const floorList = require('../util/all_info.json')
        const watchList = floorList.find(floor=>(floor.fid===fid)).watchList
        //人为制造异步
        setTimeout(()=>{
            dispatch(queryAllInfoByFloor(watchList))
        },500)
    }
}

export const queryNewsDetail=(newsDetail)=>{
    return {
        type:QUERY_NEWS_DETAILS,
        payload:newsDetail
    }
}
//异步的actioncreator
export const queryNewsDetailAsync=(id)=>{
    return (dispatch)=>{
        const newsDetails = require('../util/all_news_details.json')
        
        let newsDetail = newsDetails.find((nd)=>(nd.id===id))
        
        //人为制造异步
        setTimeout(()=>{
            dispatch(queryNewsDetail(newsDetail))
        },500)
    }
}

export const queryAllNewsByType=(newsList,pageIndex)=>{
    return {
        type:QUERY_ALL_NEWS_BYTYPE,
        payload:{
            newsList,
            pageIndex
        }
    }
}
//异步的actioncreator
export const queryAllNewsByTypeAsync=(type='fireproofing',pageIndex=1,pageSize=7)=>{
    //分页查询新闻列表
    return (dispatch)=>{
        let newsList = require('../util/all_news.json')
        const newsList2 = []
        newsList = newsList.filter((cnews)=>{
            return cnews.type===type
        })
        
        if((pageIndex-1)*pageSize<newsList.length){
            
            for(let i=(pageIndex-1)*pageSize;i<pageSize*pageIndex;i++){
                newsList2.push(newsList[i])
            }
        }
        
        //人为制造异步
        setTimeout(()=>{
            dispatch(queryAllNewsByType(newsList2,pageIndex))
        },500)
    }
}

//同步的actioncreator
export const queryAllTopNews=(topNewsList)=>{
    return {
        type:QUERY_ALL_TOPNEWS,
        payload:topNewsList
    }
}
//异步的actioncreator
export const queryAllTopNewsAsync=()=>{
    return (dispatch)=>{
        const topNewsList = require('../util/top_news.json')
        //人为制造异步
        setTimeout(()=>{
            dispatch(queryAllTopNews(topNewsList))
        },500)
    }
    
}